package com.breeze.blockchain.common.aop;

import com.alibaba.fastjson2.JSON;
import com.breeze.blockchain.mybatis.entity.OperationLogDo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 操作日志记录处理
 *
 * @author breeze
 */
@Aspect
@Component
@Slf4j
public class AppAccessLogAspect {

  /**
   * 处理完请求后执行
   *
   * @param joinPoint 切点
   */
  @AfterReturning(
      pointcut = "execution(public * com.breeze.blockchain.controller.app.*.*(..))",
      returning = "jsonResult")
  public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
    handleLog(joinPoint, null, jsonResult);
  }

  /**
   * 拦截异常操作
   *
   * @param joinPoint 切点
   * @param e 异常
   */
  @AfterThrowing(
      value = "execution(public * com.breeze.blockchain.controller.app.*.*(..))",
      throwing = "e")
  public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
    handleLog(joinPoint, e, null);
  }

  protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
    try {
      if (log.isInfoEnabled()) {
        OperationLogDo operationLog = new OperationLogDo();
        operationLog.fillAppOperatorInfo();
        operationLog.fillRequestInfo(joinPoint, jsonResult);
        operationLog.fillStatus(e);
        operationLog.fillAccessLogInfo(joinPoint);
        log.info(JSON.toJSONString(operationLog));
      }
    } catch (Exception exp) {
      log.error("写入操作日式失败", exp);
    }
  }
}
